package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.mappers.RecommendMapper;
import com.burgeon.backend.SHOPBACKEND.service.BackendRecommendService;
import com.burgeon.backend.SHOPBACKEND.service.ex.DataNotFoundException;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@Service
public class BackendRecommendServiceImpl implements BackendRecommendService {
    @Autowired
    private RecommendMapper recommendMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private AccountMapper accountMapper;
    /**
     * 获取推荐的开关和值（优惠券和积分）
     * @param account
     * @return
     */
    @Override
    public RecommendSwitch findRecommendSwitchByAccount(String account) {
        RecommendSwitch recommendSwitch = recommendMapper.findRecommendSwitchByAccount(account);
//        recommendSwitch.setRSwitch1(recommendSwitch.getRSwitch1().equals("Y") ? "1" : "2");
//        recommendSwitch.setRSwitch4(recommendSwitch.getRSwitch4().equals("Y") ? "1" : "2");

//        couponMapper.findCouponTypeById(recommendSwitch.getRValue1());//推荐优惠券
//        couponMapper.findCouponTypeById(recommendSwitch.getRValue4());//新用户优惠券
        return recommendSwitch;
    }

    public Integer addRecommendCode(MultipartFile recommendImg,MultipartFile newImg, String name,String account){
        if (null == recommendImg || recommendImg.isEmpty()) {
            System.err.println("文件为空");
            throw new UploadException("推荐图片为空");
        }else if (null == newImg || newImg.isEmpty()){
            throw new UploadException("新用户注册图片为空");
        }
        //查询是否有推荐配置信息
        RecommendConfig recommendConfig = recommendMapper.getRecommendConfigByAccount(account);
        //保存文件
        String recommendUrl = createFile(recommendImg,account,"recommendImg");
        String newUrl=createFile(newImg,account,"newImg");
        if(recommendConfig ==null){
            String token = accountMapper.GetTokenForAccount(account);
            //新增配置信息
            Integer config = recommendMapper.addRecommendConfig(recommendUrl,newUrl,name,account,token);
            if(config==0){
                throw new DataNotFoundException("添加配置信息失败");
            }
        }
        //修改配置信息
        Integer config = recommendMapper.updateRecommendConfig(recommendUrl,newUrl,name,account);
        if(config==0){
            throw new DataNotFoundException("修改配置信息失败");
        }
        return  config;
    }

    @Override
    public Integer updateRecommendCode(MultipartFile recommendImg,MultipartFile newImg, String name, String account) {
        if (null == recommendImg || recommendImg.isEmpty()) {
            System.err.println("文件为空");
            throw new UploadException("推荐图片为空");
        }else if (null == newImg || newImg.isEmpty()){
            throw new UploadException("新用户注册图片为空");
        }

        String recommendUrl = createFile(recommendImg,account,"recommendImg");
        String newUrl=createFile(newImg,account,"newImg");
        Integer config = recommendMapper.updateRecommendConfig(recommendUrl,newUrl,name,account);
        if(config==0) {
            throw new DataNotFoundException("添加配置信息失败");
        }
        return config;
    }

    @Override
    public Integer updateRecommendSwitch( String rSwitch1, String rValue1, String rSwitch2, String rValue2,
                                         String rSwitch3, String rValue3, String rSwitch4, String rValue4, String account) {

        Integer row = recommendMapper.updateRecommendSwitch(rSwitch1, rValue1, rSwitch2, rValue2,
                rSwitch3, rValue3, rSwitch4, rValue4, account);
        if(row==0){
            throw new DataNotFoundException("添加配置信息失败");
        }

        return row;
    }

    private String createFile(MultipartFile file,String account,String type){
        //文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "//root//code//img//" + account + "//recommendConfig//" ;
        // 新文件名
        fileName = type + suffixName;
        saveFile(file, fileName, filePath);
        String url="http://lfwdcdn.cloudsmicro.com/img/" + account + "/recommendConfig/" + fileName;
        return url;
    }

    //保存文件
    private void saveFile(MultipartFile multipartFile, String fileName, String filePath) {
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        }
    }


    @Override
    public RecommendVo getRecommend(String account,int page) {
        int start = (page - 1)*20;
        ArrayList<Recommend> recommendArrayList = new ArrayList<>();
        String count = recommendMapper.getRecommendCount(account);
        //分页查询推荐信息
        ArrayList<Recommend> recommends = recommendMapper.getRecommend(account,start);
        System.err.println(recommends);
        if(recommends.size()>0){
            for (Recommend recommend:recommends) {
                System.err.println(recommend.getPresentee());
                //被推荐者的信息
                RecommendUser recommendUser = recommendMapper.findUserById(recommend.getPresentee());
                if(recommendUser != null){
                    System.err.println(recommendUser);
                    recommend.setPresenteeName(recommendUser.getName());
                    recommend.setPresenteeImg(recommendUser.getHeadimg());
                }
                //推荐者的信息
                RecommendUser recommendUserRe = recommendMapper.findUserById(recommend.getReferrer());
                if(null != recommendUserRe){
                    recommend.setReferrerName(recommendUserRe.getName());
                    recommend.setReferrerImg(recommendUserRe.getHeadimg());
                    recommend.setReferrerVipType(recommendUserRe.getVipType());
                    recommend.setStore(recommendUserRe.getStore());

                }
                recommendArrayList.add(recommend);
            }
        }
        RecommendVo recommendVo = new RecommendVo();
        recommendVo.setRecommends(recommendArrayList);
        recommendVo.setCount(count);
        return recommendVo;
    }

    /**
     * 搜索
     * @param name
     * @param account
     * @return
     */
    @Override
    public ArrayList<Recommend> findUserByName(String name, String account) {
//        int start = (page - 1)*20;
        ArrayList<Recommend> recommendArrayList = new ArrayList<>();
        //根据名字查找
        ArrayList<String> recommendUsers = recommendMapper.findUserByName(name,account);
//        System.err.println(recommendUsers);
//        if(recommendUsers == null){
//            throw new DataNotFoundException("没有用户");
//        }
        for (String pId:recommendUsers) {
            //根据uid寻找推荐信息
            ArrayList<Recommend> recommends = recommendMapper.findRecommendByRefer(pId);
//            if(recommends == null){
//                throw new DataNotFoundException("用户没有推荐信息");
//            }
            if(recommends.size()>0){
                for (Recommend recommend:recommends) {
                    System.err.println(recommend.getPresentee());
                    //被推荐者的信息
                    RecommendUser presenteeUser = recommendMapper.findUserById(recommend.getPresentee());
                    if(presenteeUser != null){
                        System.err.println(presenteeUser);
                        recommend.setPresenteeName(presenteeUser.getName());
                        recommend.setPresenteeImg(presenteeUser.getHeadimg());
                    }

                    //推荐者的信息
                    RecommendUser recommendUserRe = recommendMapper.findUserById(recommend.getReferrer());
                    if(recommendUserRe != null){
                        recommend.setReferrerName(recommendUserRe.getName());
                        recommend.setReferrerImg(recommendUserRe.getHeadimg());
                        recommend.setReferrerVipType(recommendUserRe.getVipType());
                        recommend.setStore(recommendUserRe.getStore());
                    }

                    recommendArrayList.add(recommend);
                }
            }

        }
        return recommendArrayList;
    }

    /**
     * 获取推荐配置信息
     * @param account
     * @return
     */
    @Override
    public RecommendConfig getRecommendConfigByAccount(String account) {
        //获取奖励开关
//        RecommendSwitch recommendSwitch = recommendMapper.findRecommendSwitchByAccount(account);
        //获取推荐图配置
        RecommendConfig recommendConfig = recommendMapper.getRecommendConfigByAccount(account);
        if(recommendConfig != null){
            if(recommendConfig.getRecommendUrl()==null){
                recommendConfig.setRecommendUrl("http://lfwdcdn.cloudsmicro.com/img/recommend/recommend.png");
            }
            if(recommendConfig.getNewUrl() ==null){
                recommendConfig.setNewUrl("http://lfwdcdn.cloudsmicro.com/img/recommend/recommend2.png");
            }
        }else{
            RecommendConfig recommendConfig1 = new RecommendConfig();
            recommendConfig1.setRecommendUrl("http://lfwdcdn.cloudsmicro.com/img/recommend/recommend.png");
            recommendConfig1.setNewUrl("http://lfwdcdn.cloudsmicro.com/img/recommend/recommend2.png");
        }
//        recommendConfig.setRecommendSwitch(recommendSwitch);
        return recommendConfig;
    }
}
